﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 订单信息
    /// </summary>
    [Route("admin/order")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly IOrderService _orderService;
        private readonly IOrderCollectionService _orderCollectionService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        /// <summary>
        /// 依赖注入
        /// </summary>
        public OrderController(IOrderService orderService, IOrderCollectionService orderCollectionService, IUserService userService, IMapper mapper)
        {
            _orderService = orderService;
            _orderCollectionService = orderCollectionService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/admin/order/1
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //查询数据库获取实体
            var model = await _orderService.QueryAsync(x => x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrdersDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取总记录数量
        /// 示例：/admin/order/view/count
        /// </summary>
        [HttpGet("view/count")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.View)]
        public async Task<IActionResult> GetCount([FromQuery] OrderParameter searchParam)
        {
            var result = await _orderService.QueryCountAsync(
                x => (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (searchParam.PaymentStatus < 0 || x.PaymentStatus == searchParam.PaymentStatus)
                && (searchParam.DeliveryStatus < 0 || x.DeliveryStatus == searchParam.DeliveryStatus)
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0));
            //返回成功200
            return Ok(result);
        }

        /// <summary>
        /// 获取总记录金额
        /// 示例：/admin/order/view/amount
        /// </summary>
        [HttpGet("view/amount")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.View)]
        public async Task<IActionResult> GetAmount([FromQuery] OrderParameter searchParam)
        {
            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddHours(-DateTime.Now.Hour + 1);
            }
            var result = await _orderService.QueryAmountAsync(
                x => (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0));
            //返回成功200
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/admin/order/view/10
        /// </summary>
        [HttpGet("view/{top}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.View)]
        public async Task<IActionResult> GetList([FromRoute] int top, [FromQuery] OrderParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }

            //获取数据库列表
            var resultFrom = await _orderService.QueryListAsync(top,
                 x => (searchParam.MerchantId <= 0 || x.MerchantId == searchParam.MerchantId)
                && (searchParam.OrderType < 0 || x.OrderType == searchParam.OrderType)
                && (searchParam.PaymentId <= 0 || (x.CollectionRelations != null && x.CollectionRelations.Any(x => x.Collection!.PaymentId == searchParam.PaymentId)))
                && (searchParam.DeliveryId <= 0 || x.DeliveryId == searchParam.DeliveryId)
                && (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (searchParam.EndTime == null || DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrdersDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/admin/order?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] OrderParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _orderService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => (searchParam.MerchantId <= 0 || x.MerchantId == searchParam.MerchantId)
                && (searchParam.OrderType < 0 || x.OrderType == searchParam.OrderType)
                && (searchParam.PaymentId <= 0 || (x.CollectionRelations != null && x.CollectionRelations.Any(x => x.Collection!.PaymentId == searchParam.PaymentId)))
                && (searchParam.DeliveryId <= 0 || x.DeliveryId == searchParam.DeliveryId)
                && (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (searchParam.EndTime == null || DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrdersDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加订单
        /// 示例：/admin/order
        /// </summary>
        [HttpPost]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Add)]
        public async Task<IActionResult> Add([FromBody] OrdersAddDto modelDto)
        {
            //保存数据
            var result = await _orderService.AddAsync(modelDto);
            return Ok(result);
        }

        /// <summary>
        /// 修改订单
        /// 示例：/admin/order/1
        /// </summary>
        [HttpPut("{id}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] OrdersEditDto modelDto)
        {
            //保存数据
            var result = await _orderService.UpdateAsync(x => x.Id == id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 确认收款(管理员)
        /// 示例：/admin/order/confirm/TN2011233211...
        /// </summary>
        [HttpPut("confirm/{tradeNo}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Confirm)]
        public async Task<IActionResult> Confirm([FromRoute] string tradeNo)
        {
            //保存数据
            var result = await _orderCollectionService.ConfirmAsync(tradeNo);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }

        /// <summary>
        /// 签收订单(管理员)
        /// 示例：/admin/order/receipt/1
        /// </summary>
        [HttpPut("receipt/{id}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Complete)]
        public async Task<IActionResult> Receipt([FromRoute] long id)
        {
            //保存数据
            var result = await _orderService.ReceiptAsync(x => x.Id == id);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }

        /// <summary>
        /// 完成订单(管理员)
        /// 示例：/admin/order/complete/1
        /// </summary>
        [HttpPut("complete/{id}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Complete)]
        public async Task<IActionResult> Complete([FromRoute] long id)
        {
            //保存数据
            var result = await _orderService.CompleteAsync(x => x.Id == id);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }

        /// <summary>
        /// 作废订单(管理员)
        /// 示例：/admin/order/invalid/1
        /// </summary>
        [HttpPut("invalid/{id}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Invalid)]
        public async Task<IActionResult> Invalid([FromRoute] long id)
        {
            //保存数据
            var result = await _orderService.InvalidAsync(x => x.Id == id);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/admin/order/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] int id)
        {
            if (await _orderService.ExistsAsync<Orders>(x => x.Id == id && x.Status <= 5))
            {
                return BadRequest(ResponseMessage.Error($"订单已删除或在交易中"));
            }
            var result = await _orderService.DeleteAsync(x => x.Id == id && x.Status > 5);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/admin/order?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("Order", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _orderService.DeleteAsync(x => x.Status > 5 && arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion

        #region 商家调用接口============================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/merchant/order/1
        /// </summary>
        [HttpGet("/merchant/order/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //查询数据库获取实体
            var model = await _orderService.QueryAsync(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据[{id}]不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrdersDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取总记录数量
        /// 示例：/merchant/order/view/count
        /// </summary>
        [HttpGet("/merchant/order/view/count")]
        [Authorize]
        public async Task<IActionResult> MerchantGetCount([FromQuery] OrderParameter searchParam)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            var result = await _orderService.QueryCountAsync(
                x => x.MerchantId == merchantModel.Id
                && (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (searchParam.PaymentStatus < 0 || x.PaymentStatus == searchParam.PaymentStatus)
                && (searchParam.DeliveryStatus < 0 || x.DeliveryStatus == searchParam.DeliveryStatus)
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0));
            //返回成功200
            return Ok(result);
        }

        /// <summary>
        /// 获取总记录金额
        /// 示例：/merchant/order/view/amount
        /// </summary>
        [HttpGet("/merchant/order/view/amount")]
        [Authorize]
        public async Task<IActionResult> MerchantGetAmount([FromQuery] OrderParameter searchParam)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            if (searchParam.StartTime == null)
            {
                searchParam.StartTime = DateTime.Now.AddHours(-DateTime.Now.Hour + 1);
            }
            var result = await _orderService.QueryAmountAsync(
                x => x.MerchantId == merchantModel.Id
                && (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0));
            //返回成功200
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/merchant/order/view/10
        /// </summary>
        [HttpGet("/merchant/order/view/{top}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromRoute] int top, [FromQuery] OrderParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据库列表
            var resultFrom = await _orderService.QueryListAsync(top,
                x => x.IsDelete == 0
                && x.MerchantId == merchantModel.Id
                && (searchParam.OrderType < 0 || x.OrderType == searchParam.OrderType)
                && (searchParam.PaymentId <= 0 || (x.CollectionRelations != null && x.CollectionRelations.Any(x => x.Collection!.PaymentId == searchParam.PaymentId)))
                && (searchParam.DeliveryId <= 0 || x.DeliveryId == searchParam.DeliveryId)
                && (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (searchParam.EndTime == null || DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrdersDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/merchant/order?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/merchant/order")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromQuery] OrderParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _orderService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.IsDelete == 0
                && x.MerchantId == merchantModel.Id
                && (searchParam.OrderType < 0 || x.OrderType == searchParam.OrderType)
                && (searchParam.PaymentId <= 0 || (x.CollectionRelations != null && x.CollectionRelations.Any(x => x.Collection!.PaymentId == searchParam.PaymentId)))
                && (searchParam.DeliveryId <= 0 || x.DeliveryId == searchParam.DeliveryId)
                && (searchParam.Status <= 0 || x.Status == searchParam.Status)
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (searchParam.EndTime == null || DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrdersDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 修改订单
        /// 示例：/merchant/order/1
        /// </summary>
        [HttpPut("/merchant/order/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantUpdate([FromRoute] long id, [FromBody] OrdersEditDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //保存数据
            var result = await _orderService.UpdateAsync(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id, modelDto);
            return NoContent();
        }

        /// <summary>
        /// 签收订单
        /// 示例：/merchant/order/receipt/1
        /// </summary>
        [HttpPut("/merchant/order/receipt/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantReceipt([FromRoute] long id)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //保存数据
            var result = await _orderService.ReceiptAsync(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }

        /// <summary>
        /// 作废订单
        /// 示例：/merchant/order/invalid/1
        /// </summary>
        [HttpPut("/merchant/order/invalid/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantInvalid([FromRoute] long id)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //保存数据
            var result = await _orderService.InvalidAsync(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/merchant/order/1
        /// </summary>
        [HttpDelete("/merchant/order/{id}")]
        [Authorize]
        public async Task<IActionResult> MerchantDelete([FromRoute] long id)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            var model = await _orderService.QueryAsync<Orders>(x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && x.Id == id);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"记录[{id}]不存在或已删除"));
            }
            model.IsDelete = 1; //标记删除
            //保存到数据库
            await _orderService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录(级联数据)
        /// 示例：/merchant/order?ids=1,2,3
        /// </summary>
        [HttpDelete("/merchant/order")]
        [Authorize]
        public async Task<IActionResult> MerchantDeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _orderService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //找出符合条件的记录
            var list = await _orderService.QueryListAsync<Orders>(1000, x => x.IsDelete == 0 && x.MerchantId == merchantModel.Id && arrIds.Contains(x.Id), WriteRoRead.Write);
            if (list.Count() == 0)
            {
                return BadRequest(ResponseMessage.Error("没有找到需要删除的记录"));
            }
            foreach (var item in list)
            {
                item.IsDelete = 1; //标记删除
            }
            //保存到数据库
            await _orderService.SaveAsync();

            return NoContent();
        }
        #endregion

        #region 当前账户调用接口========================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/account/order/1
        /// </summary>
        [HttpGet("/account/order/{id}")]
        [Authorize]
        public async Task<IActionResult> AccountGetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            //查询数据库获取实体
            var model = await _orderService.QueryAsync(x => x.IsDelete == 0 && x.UserId == userId && x.Id == id);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"订单[{id}]不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrdersDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 根据订单货品ID获取数据
        /// 示例：/account/order/goods/1
        /// </summary>
        [HttpGet("/account/order/goods/{id}")]
        [Authorize]
        public async Task<IActionResult> AccountGetByGoodsId([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrderGoodsDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            //查询数据库获取实体
            var model = await _orderService.QueryGoodsAsync(x => x.Id == id && x.Order != null && x.Order.IsDelete == 0 && x.Order.UserId == userId);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"订单不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrderGoodsDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 根据订单号获取数据
        /// 示例：/account/orderno/PN2021031...
        /// </summary>
        [HttpGet("/account/orderno/{orderNo}")]
        [Authorize]
        public async Task<IActionResult> AccountGetByNo([FromRoute] string orderNo, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            //查询数据库获取实体
            var model = await _orderService.QueryAsync(x => x.IsDelete == 0 && x.UserId == userId && x.OrderNo == orderNo, WriteRoRead.Write);
            if (model == null)
            {
                return NotFound(ResponseMessage.Error($"订单{orderNo}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<OrdersDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/account/order/view/10
        /// </summary>
        [HttpGet("/account/order/view/{top}")]
        [Authorize]
        public async Task<IActionResult> AccountGetList([FromRoute] int top, [FromQuery] OrderParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }

            //获取数据库列表
            var resultFrom = await _orderService.QueryListAsync(top,
                x => x.IsDelete == 0
                && x.UserId == userId
                && (searchParam.MerchantId <= 0 || x.MerchantId == searchParam.MerchantId)
                && (searchParam.OrderType < 0 || x.OrderType == searchParam.OrderType)
                && (searchParam.PaymentId <= 0 || (x.CollectionRelations != null && x.CollectionRelations.Any(x => x.Collection!.PaymentId == searchParam.PaymentId)))
                && (searchParam.DeliveryId <= 0 || x.DeliveryId == searchParam.DeliveryId)
                && (searchParam.Status != 1 || x.Status == 1)
                && (searchParam.Status != 2 || x.Status == 2)
                && (searchParam.Status != 3 || (x.Status == 3 || x.Status == 4))
                && (searchParam.Status != 4 || x.Status == 5 && x.OrderGoods.Any(g => g.EvaluateStatus == 0))
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (searchParam.EndTime == null || DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrdersDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/account/order?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/account/order")]
        [Authorize]
        public async Task<IActionResult> AccountGetList([FromQuery] OrderParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<OrdersDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的塑性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _orderService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.IsDelete == 0
                && x.UserId == userId
                && (searchParam.MerchantId <= 0 || x.MerchantId == searchParam.MerchantId)
                && (searchParam.OrderType < 0 || x.OrderType == searchParam.OrderType)
                && (searchParam.PaymentId <= 0 || (x.CollectionRelations != null && x.CollectionRelations.Any(x => x.Collection!.PaymentId == searchParam.PaymentId)))
                && (searchParam.DeliveryId <= 0 || x.DeliveryId == searchParam.DeliveryId)
                && (searchParam.Status != 1 || x.Status == 1)
                && (searchParam.Status != 2 || x.Status == 2)
                && (searchParam.Status != 3 || (x.Status == 3 || x.Status == 4))
                && (searchParam.Status != 4 || x.Status == 5 && x.OrderGoods.Any(g => g.EvaluateStatus == 0))
                && (searchParam.StartTime == null || DateTime.Compare(x.AddTime, searchParam.StartTime.GetValueOrDefault()) >= 0)
                && (searchParam.EndTime == null || DateTime.Compare(x.AddTime, searchParam.EndTime.GetValueOrDefault()) <= 0)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<OrdersDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加订单
        /// 示例：/account/order
        /// </summary>
        [HttpPost("/account/order")]
        [Authorize]
        public async Task<IActionResult> AccountAdd([FromBody] OrdersAddDto modelDto)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }
            modelDto.UserId = userId;
            if (modelDto.OrderList.Count == 0)
            {
                return BadRequest(ResponseMessage.Error("没有需要结算的订单，请确认后操作"));
            }
            //保存数据
            var result = await _orderService.AddAsync(modelDto);
            return Ok(result);
        }

        /// <summary>
        /// 取消订单(客户)
        /// 示例：/account/order/cancel/1
        /// </summary>
        [HttpPut("/account/order/cancel/{id}")]
        [Authorize]
        public async Task<IActionResult> Cancel([FromRoute] long id)
        {
            //保存数据
            var result = await _orderService.CancelAsync(id);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }

        /// <summary>
        /// 确认收货(客户)
        /// 示例：/account/order/confirm/1
        /// </summary>
        [HttpPut("/account/order/confirm/{id}")]
        [Authorize]
        public async Task<IActionResult> Confirm([FromRoute] long id)
        {
            //保存数据
            var result = await _orderService.ConfirmAsync(id);
            if (result)
            {
                return NoContent();
            }
            return BadRequest(ResponseMessage.Error("保存过程中发生了错误"));
        }
        #endregion
    }
}